<?php

class Schet extends Controller {

	function index()
	{
		$scheta = $this->MSchet->getList(array('user_id' => Auth::$user_id));
		$this->load->view('head');
		$this->load->view('schet/index', array('scheta' => $scheta));
		$this->load->view('foot');
	}

	function add_small()
	{
		$id = 0;
		if(@$_POST['name'])
		{
			$save = array(
				'name' => trim($_POST['name']),
				'valuta' => trim($_POST['valuta']),
				'user_id' => Auth::$user_id,
			);
			$this->MSchet->save($save, $id);
		}
		$this->load->view('head', array('small' => true));
		$this->load->view('schet/add_small', array('id' => $id));
		$this->load->view('foot');
	}

	function edit($id = 0)
	{
		$id = intval($id);
		$schet = $this->MSchet->get($id);
		if(@$schet['id'] && $schet['user_id'] != Auth::$user_id)
		{
			return;
		}
		$this->load->view('head');
		$this->load->view('schet/edit', array('schet' => $schet));
		$this->load->view('foot');
	}

	function save()
	{
		$id = intval($_POST['id']);
		$schet = $this->MSchet->get($id);
		if($schet['id'] && $schet['user_id'] != Auth::$user_id)
		{
			return;
		}
		$save = array(
			'name' => trim($_POST['name']),
			'valuta' => trim($_POST['valuta']),
			'user_id' => Auth::$user_id,
		);
		$this->MSchet->save($save, $id);
		redirect('schet');
	}

	function fix()
	{
		$scheta = $this->MSchet->getList(array('user_id' => Auth::$user_id));
		$info = array();
		foreach($scheta as $k => $schet)
		{
			$info[$schet['id']] = $this->_getInfoFixBySchet($schet['id']);
			if($info[$schet['id']]['last_date'] && date("d.m.Y", strtotime($info[$schet['id']]['last_date'])) == date('d.m.Y'))
			{
				unset($scheta[$k]);
			}
		}
		$this->load->model('MSetting');
		$setting = $this->MSetting->getMe();
		$this->load->view('head');
		$this->load->view('schet/fix', array('scheta' => $scheta, 'info' => $info, 'setting' => $setting));
		$this->load->view('foot');
	}

	function fix_save()
	{
		global $IMAGE_FILES;
		$schet_id = intval($_POST['schet_id']);
		$schet = $this->MSchet->get($schet_id);
		if($schet['id'] && $schet['user_id'] != Auth::$user_id)
		{
			return;
		}
		$error = '';
		if(@$_FILES['file']['name'] && is_uploaded_file($_FILES['file']['tmp_name']))
		{
			$ex = strtolower(end(explode(".", $_FILES['file']['name'])));
			if(in_array($ex, $IMAGE_FILES))
			{
				$filename = Auth::$user_id."_".md5(microtime()).".".$ex;
				if(move_uploaded_file($_FILES['file']['tmp_name'], UPLOAD_PATH.$filename))
				{
				}
				else
				{
					$error = 'Ошибка при загрузке файла. Попробуйте ещё раз.';
				}
			}
			else
			{
				$error = 'Файл, подтверждающий сумму на счёте должен быть обязательно изображением';
			}
		}
		else
		{
			$error = 'Вы должны обязательно загрузить файл, подтверждающий сумму на счёте';
		}
		if($error)
		{
			$this->session->set_flashdata('system_error', $error);
		}
		else
		{
			$info = $this->_getInfoFixBySchet($schet_id);
			$save = array(
				'schet_id' => $schet['id'],
				'date' => date("Y-m-d H:i:s"),
				'summ' => $info['current_summ'],
				'comment' => trim(@$_POST['comment']),
				'file' => $filename,
				'last_platezh_id' => $info['last_platezh_id'],
			);
			$id = 0;
			$this->MSchetFix->save($save, $id);
		}
		redirect('schet/fix');
	}

	function fix_history()
	{
		$time_from = strtotime("-1 week");
		$time_to = time();
		$filter = array(
			'user_id' => Auth::$user_id,
			'day_from' => date("j", $time_from),
			'month_from' => date("n", $time_from),
			'year_from' => date("Y", $time_from),
			'day_to' => date("j", $time_to),
			'month_to' => date("n", $time_to),
			'year_to' => date("Y", $time_to),
		);

		if(isset($_GET['valuta']))
		{
			$filter = $_GET;
			if(@!$filter['user_id'] || !$this->MUser->inMyStructure($filter['user_id']))
			{
				$filter['user_id'] = Auth::$user_id;
			}
			$user = $this->MUser->get($filter['user_id']);
			$allusers = array($user['id'] => $user);
			if(@$filter['include_children'])
			{
				$user['children'] = $this->MUser->getMyStructure($filter['user_id']);
				$user_structure = array($user['id'] => $user);
				$children_and_me = userGetArrayIndexByStructure($user_structure);
				$allusers = $children_and_me;
				$filter['user_id'] = array_keys($children_and_me);
			}
			$this->session->set_flashdata('fix_history_filter', $_SERVER['QUERY_STRING']);
		}
		else
		{
			$user = $this->MUser->get($filter['user_id']);
			$allusers = array($user['id'] => $user);
		}
		$me = $filter['user_id'] == Auth::$user_id ? $user : $this->MUser->get(Auth::$user_id);
		$me['children'] = $this->MUser->getMyStructure($me['id']);
		$structure = array();
		$structure[$me['id']] = $me;

		$schet_filters = array('user_id' => $filter['user_id']);
		if(@$filter['valuta'])
		{
			$schet_filters['valuta'] = $filter['valuta'];
		}
		$scheta = $this->MSchet->getList($schet_filters);

		$fixes_filters = array('sort' => 'date desc');
		if(count($scheta))
		{
			$fixes_filters['schet_id'] = array_keys($scheta);
		}
		else
		{
			$fixes_filters['id'] = -1;
		}
		if(@$filter['day_from'] && @$filter['month_from'] && @$filter['year_from'])
		{
			$fixes_filters['date>='] = dateToDb($filter['year_from']."-".$filter['month_from']."-".$filter['day_from'])." 00:00:00";
		}
		if(@$filter['day_to'] && @$filter['month_to'] && @$filter['year_to'])
		{
			$fixes_filters['date<='] = dateToDb($filter['year_to']."-".$filter['month_to']."-".$filter['day_to'])." 23:59:59";
		}
		$fixes = $this->MSchetFix->getList($fixes_filters);

		$this->load->model('MSetting');
		$setting = $this->MSetting->getMe();

		$this->load->view('head');
		$this->load->view('schet/fix_history', array('filter' => $filter, 'fixes' => $fixes, 'scheta' => $scheta, 'user' => $user, 'me' => $me, 'structure' => $structure, 'allusers' => $allusers, 'setting' => $setting));
		$this->load->view('foot');
	}

	function fix_edit($fix_id = 0)
	{
		$fix_id = intval($fix_id);
		$fix = $this->MSchetFix->get($fix_id);
		$schet = $this->MSchet->get(@$fix['schet_id']);
		if(!@$schet['user_id'] || !$this->MUser->inMyStructure($schet['user_id']))
		{
			return;
		}
		$me = $this->MUser->get(Auth::$user_id);
		if(!$fix['id'] || !canEdit($schet['user_id'], $me))
		{
			return;
		}

		$session_filter = $this->session->flashdata('fix_history_filter');
		$this->session->keep_flashdata('fix_history_filter');

		$scheta = $this->MSchet->getList(array('user_id' => $schet['user_id']));
		$last_url = @$_SERVER['HTTP_REFERER'];

		$this->load->model('MSetting');
		$setting = $this->MSetting->getMe();

		$this->load->view('head');
		$this->load->view('schet/fix_edit', array('fix' => $fix, 'scheta' => $scheta, 'last_url' => $last_url, 'setting' => $setting));
		$this->load->view('foot');
	}

	function fix_edit_save()
	{
		global $IMAGE_FILES;
		$fix_id = intval($_POST['id']);
		$fix = $this->MSchetFix->get($fix_id);
		$schet = $this->MSchet->get(@$fix['schet_id']);
		if(!@$schet['user_id'] || !$this->MUser->inMyStructure($schet['user_id']))
		{
			return;
		}
		$me = $this->MUser->get(Auth::$user_id);
		if(!$fix['id'] || !canEdit($schet['user_id'], $me))
		{
			return;
		}

		$new_schet_id = $_POST['schet_id'];
		if($new_schet_id != $schet['id'])
		{
			$new_schet = $this->MSchet->get($new_schet_id);
			if(!@$new_schet['id'] || $new_schet['user_id'] != $schet['user_id'])
			{
				return;
			}
		}

		$date = dateToDb($_POST['year']."-".$_POST['month']."-".$_POST['day']).' '.($_POST['hour'] < 10 ? "0" : '').$_POST['hour'].":".($_POST['minute'] < 10 ? "0" : '').$_POST['minute'].":00";
		$save = array(
			'schet_id' => $new_schet_id,
			'date' => $date,
			'comment' => trim($_POST['comment'])
		);

		$error = '';
		if(@$_FILES['file']['name'] && is_uploaded_file($_FILES['file']['tmp_name']))
		{
			$ex = strtolower(end(explode(".", $_FILES['file']['name'])));
			if(in_array($ex, $IMAGE_FILES))
			{
				$filename = Auth::$user_id."_".md5(microtime()).".".$ex;
				if(move_uploaded_file($_FILES['file']['tmp_name'], UPLOAD_PATH.$filename))
				{
					$save['file'] = $filename;
				}
				else
				{
					$error = 'Ошибка при загрузке файла. Попробуйте ещё раз.';
				}
			}
			else
			{
				$error = 'Файл, подтверждающий сумму на счёте должен быть обязательно изображением';
			}
		}

		if($error)
		{
			$this->session->set_flashdata('system_error', $error);
		}
		else
		{
			if(@$save['file'])
			{
				@unlink(UPLOAD_PATH.$fix['file']);
			}
			$this->MSchetFix->save($save, $fix['id']);
		}

		if($_POST['last_url'])
		{
			$url = str_replace(";=", "=", $_POST['last_url']);
			header('Location: '.$url);
		}
		else
		{
			redirect('schet/fix_history/');
		}
	}

	function fix_delete($fix_id = 0)
	{
		$fix_id = intval($fix_id);
		$fix = $this->MSchetFix->get($fix_id);
		$schet = $this->MSchet->get(@$fix['schet_id']);
		if(!@$schet['user_id'] || !$this->MUser->inMyStructure($schet['user_id']))
		{
			return;
		}
		$me = $this->MUser->get(Auth::$user_id);
		if(!$fix['id'] || !canDelete($schet['user_id'], $me))
		{
			return;
		}

		@unlink(UPLOAD_PATH.$fix['file']);
		$this->MSchetFix->delete($fix['id']);
		if($_SERVER['HTTP_REFERER'])
		{
			header('Location: '.$_SERVER['HTTP_REFERER']);
		}
		else
		{
			redirect('schet/fix_history/');
		}
	}


	function &_getInfoFixBySchet($schet_id)
	{
		$last_fix = $this->MSchetFix->getLast($schet_id);
		$info['last_summ'] = @$last_fix['summ'];
		$info['last_date'] = @$last_fix['date'];
		$last_platezh_id = intval(@$last_fix['last_platezh_id']);
		$last_time = @$last_fix['date'] ? strtotime($last_fix['date']) : 0;
		$platezhi = $this->MPlatezh->getList(array('schet_id' => $schet_id, 'id>' => $last_platezh_id, 'sort' => 'from_date desc'));
		$balance = 0;
		foreach($platezhi as $kk => $p)
		{
			$koef_komiss = isPlatezhBuy($p) ? -1 : 1;
			$p['itogo'] = $p['summ'] + $koef_komiss * $p['komiss'];
			$koef_itogo = isPlatezhBuy($p) ? 1 : -1;
			$balance += $koef_itogo * $p['itogo'];
			platezhFromTo($p);
			$platezhi[$kk] = $p;
			$last_platezh_id = max($last_platezh_id, $p['id']);
		}
		$info['balance'] = $balance;
		$info['platezhi'] = $platezhi;
		$info['current_summ'] = round(floatval($info['last_summ']) + floatval($balance), 2);
		$info['last_platezh_id'] = $last_platezh_id;
		return $info;
	}

	
}

